package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.ExerciseDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Exercise;
import com.itheima.service.ExerciseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = ExerciseService.class)
@Transactional
public class ExerciseServiceImpl implements ExerciseService {

    @Autowired
    private ExerciseDao exerciseDao;

    @Override
    public void add(ArrayList<Exercise> exercises) {

        if (exercises != null) {
            for (Exercise exercise : exercises) {
                long count = exerciseDao.findExerciseName(exercise.getId());
                if (count > 0) {
                    exerciseDao.update(exercise);
                } else {
                    exerciseDao.add(exercise);
                }
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Exercise> page = exerciseDao.findBySeach(queryPageBean.getQueryString());
        long total = page.getTotal();
        List<Exercise> list = page.getResult();
        PageResult pageResult = new PageResult(total, list);
        return pageResult;

    }

    @Override
    public void addExercise(Exercise exercise) {
        exerciseDao.add(exercise);
    }

    @Override
    public List<Exercise> findAll() {
       return exerciseDao.findAll();
    }
}
